import json
from redis import asyncio as aioredis

def is_json(my_string):
    try:
        json_object = json.loads(my_string)
    except ValueError as e:
        return False
    return True

# 缓存装饰器
async def redis_get(key: str, redis: aioredis.Redis):
    cached_value = await redis.get(key)
    if cached_value:
        data = cached_value.decode("utf-8")
        if is_json(data):
            data = json.loads(data)
        return data
    return None

# 缓存装饰器
async def redis_set(key: str,data, redis: aioredis.Redis):
    if isinstance(data, list):
        data = json.dumps(data, ensure_ascii=False)
    await redis.set(key, data)

# 模糊删除
async def delete_keys(pattern,redis: aioredis.Redis):
    cursor = b'0'
    while cursor:
        cursor, keys = await redis.scan(cursor=cursor, match=pattern)
        if keys:
            await redis.delete(*keys)
